package com.example.demo.service.impl;

import com.example.demo.exception.UnknownException;
import com.example.demo.pojo.dto.InvoiceEmailDTO;
import com.example.demo.service.EmailService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * @author Ethan Blake
 * @version 1.0
 * @since 2024/8/28
 */

@Slf4j
@Service
@RequiredArgsConstructor
public class EMailServiceImpl implements EmailService {

    private final JavaMailSender mailSender;

    private final TemplateEngine templateEngine;


    @Value("${spring.mail.username}")
    private String emailFrom;


    /**
     * 发送模版短信
     *
     * @param to      接受者邮箱
     * @param subject 邮件主题
     * @param message 已经包含内容的 MimeMessage 对象
     */
    @Override
    public void sendTemplateEmail(String to, String subject, MimeMessage message) {
        try {
            if (this.emailFrom == null) {
                throw new UnknownException("缺少发送者邮箱配置");
            }

            // 创建 MimeMessageHelper 时传入已经设置内容的 MimeMessage 对象
            MimeMessageHelper helper = new MimeMessageHelper(message,"UTF-8");

            // 统一设置发件人、收件人和主题
            helper.setFrom(this.emailFrom);
            helper.setTo(to);
            helper.setSubject(subject);


            mailSender.send(message);
        } catch (MessagingException e) {
            throw new UnknownException(e.getMessage());
        }
    }


    /**
     * 发送发票下载通知邮件
     * <p>
     * TODO 这里后面需要一个发票记录的实体类对象
     *
     * @param to 接受者邮箱
     */
    @Override
    public void sendInvoiceDownloadEmail(String to) {

        // 创建MimeMessage并设置内容
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper;
        String subject = "电子发票下载";

        try {
            helper = new MimeMessageHelper(message, true, "UTF-8");
            InvoiceEmailDTO invoice = new InvoiceEmailDTO();

            invoice.setPurchaser("张梦真");
            invoice.setNumber("24312000000106801029");
            invoice.setDownloadLink("http://u.baiwang.com/EvHEO9WV0hd");
            invoice.setIssuer("上海市杨浦区公共租赁住房运营管理有限公司");
            invoice.setIssueDate("2024-04-17");
            invoice.setAmount("5211.00");

            Context context = new Context();
            context.setVariable("invoice", invoice);
            String htmlContent = templateEngine.process("email/invoice_download_notice", context);

            helper.setText(htmlContent, true);
            sendTemplateEmail(to, subject, message);

        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }

}
